package com.leyou.item.service;

import com.leyou.item.entity.TbCategory;
import com.leyou.item.mapper.CategoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    /**根据父节点id获取对应的子节点数据*/
    public List<TbCategory> queryListByParent(Long id){
        TbCategory tbCategory = new TbCategory();
        tbCategory.setParentId(id);
        return categoryMapper.select(tbCategory);
    }

    /**根据品牌id获取分类商品集合*/

    public List<TbCategory> queryCategoryByBrandId(Long id){
        return categoryMapper.queryCategoryByBrandId(id);
    }

    /**添加节点*/
    public Long addCategory(TbCategory category){
        Long parentId = category.getParentId();
        TbCategory tbCategory = categoryMapper.selectByPrimaryKey(parentId);

        if(tbCategory!=null && tbCategory.getIsParent()==0){
            tbCategory.setIsParent(1L);
            categoryMapper.updateByPrimaryKeySelective(tbCategory);
        }
        categoryMapper.insertSelective(category);
        return category.getId();
    }

    /**修改节点*/
    public void updateCategory(TbCategory category){
        categoryMapper.updateByPrimaryKeySelective(category);
    }

    /**删除节点*/
    public void deleteCategory(Long id) {
        categoryMapper.deleteByPrimaryKey(id);//删除该节点
        deleteRecursion(id);//递归删除

        //判断删除的改节点是否有父节点，有的话就把父节点的改为叶子节点
        TbCategory tbCategory = categoryMapper.selectByPrimaryKey(categoryMapper.selectByPrimaryKey(id).getParentId());
        if(tbCategory!=null) {
            tbCategory.setIsParent(0L);
            categoryMapper.updateByPrimaryKeySelective(tbCategory);
        }


    }


    /**递归删除你要删除数据的子数据*/
    public void deleteRecursion(Long id){
        TbCategory tbCategory = new TbCategory();
        tbCategory.setParentId(id);
        List<TbCategory> select = categoryMapper.select(tbCategory);
        if(select!=null&&select.size()>0){
            for (TbCategory category : select) {
                categoryMapper.deleteByPrimaryKey(category.getId());//删除父节点为这个id值得所有子节点信息
                deleteCategory(category.getId());
            }
        }
    }


    /**通过cid获取分类名称*/
    public List<String> queryCategoryNamesByCids(List<Long> cids){
        List<TbCategory> tbCategories = categoryMapper.selectByIdList(cids);
        return tbCategories.stream().map(category->category.getName()).collect(Collectors.toList());
    }

    /**
     * 通过id获取分类对象
     */
    public TbCategory queryCategoryById(Long id){
        return categoryMapper.selectByPrimaryKey(id);
    }

}
